<template>
  <div class="table-group">
    <table-group
      v-model="searchParams.group_id"
      :loading="groupLoading"
      :list="[{ name: '全部', _id: 0 }, ...(groupData?.data || [])]"
      :options="{ label: 'name', id: '_id' }"
      @on-create="onGroupCreate"
      @on-edite="onGroupEdite"
      @on-delete="onGroupDelete"
    >
      <template #header> </template>
    </table-group>

    <div class="table-group__content">
      <c-table
        row-key="_id"
        class="table-template__table"
        :loading="loading"
        :data="tableData"
        v-model:search="searchParams"
        v-model:paging="paging"
        @refresh="queryTableData"
      >
        <!-- 搜索栏 -->
        <template #search>
          <c-input v-model="searchParams._id" placeholder="请输入关键字" />
          <c-select
            v-model="searchParams.use_status"
            prefixText="使用状态："
            :optionList="ImageUseStatus"
          ></c-select>
        </template>

        <!-- 操作栏 -->
        <template #handle="{ selectionList, selectionLength }">
          <el-button type="primary" @click="hanleModal">批量上传</el-button>
          <el-button
            type="primary"
            :disabled="!selectionLength"
            @click="handleImageBatchUpdate(selectionList)"
          >
            批量修改
          </el-button>
          <!-- <el-button type="primary" :disabled="!selectionLength">批量删除</el-button> -->
        </template>

        <!-- 表格 -->
        <template #table>
          <el-table-column type="selection" width="40"></el-table-column>
          <el-table-column prop="content" label="内容" min-width="200">
            <template #default="{ row }">
              <div style="white-space: pre-wrap">{{ row.content }}</div>
            </template>
          </el-table-column>
          <el-table-column label="ID" min-width="200">
            <template #default="{ row }">
              <div>ID：{{ row._id }}</div>
              <div v-if="userType == 1">userid：{{ row.userid }}</div>
              <div>分组名称：{{ getGroupEnum?.[row.group_id] || '' }}</div>
              <div>使用状态：{{ ImageUseStatus.getLabel(row.use_status || 0) }}</div>
              <div>时间：{{ dayjs(row.create_time).format('YYYY-MM-DD HH:mm:ss') }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140" fixed="right" align="center">
            <template #default="{ row }">
              <el-button type="primary" text @click="handleUseStatus(row)">标记使用</el-button>
              <el-button type="primary" text @click="handleCopy(row)">复制</el-button>
              <el-button type="danger" text @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </template>
      </c-table>
    </div>
  </div>

  <!-- 弹窗 -->
  <c-dialog title="分组管理" :width="600" name="text-group-create">
    <text-group-create :userType="userType" @refresh="queryListGroup"></text-group-create>
  </c-dialog>

  <c-dialog title="图像管理" :width="600" name="image-batch-update"> </c-dialog>
</template>

<script setup name="el-encap.table-template">
import { ref, computed, onMounted } from 'vue';

// hooks
import { useTable } from '@/hooks/useTable/index.js';
import { useFetch } from '@/hooks/useFetch/index.js';

// components
import Sortable from 'sortablejs';
import TextGroupCreate from './text-group-create.vue';
import TableGroup from '@/components/group-menus/table-group.vue';
import { MessageBox } from '@/utils/message-box';
import { ElMessage } from 'element-plus';
import { copyText } from '@/utils/tools';

// router
import { useRouter } from 'vue-router';
const router = useRouter();

// store modal
import { useModalStore } from '@/pinia/modules/modal';
const modalStore = useModalStore();

// api
import {
  listTextGroup,
  userListTextGroup,
  delTextGroup,
  pageListText,
  pageUserListText,
  delText,
  editeStatus,
} from '@/apis/text';

import { ImageUseStatus } from '@/config/global-variable';

import dayjs from 'dayjs';

const props = defineProps({
  // 0 普通用户 1 admin
  userType: {
    type: [String, Number],
    default: 0,
  },
});

const getGroupEnum = computed(() => {
  return groupData.value.data.reduce(function (obj, item) {
    obj[item._id] = item.name;
    return obj;
  }, {});
});

// 分组列表
const {
  loading: groupLoading,
  data: groupData,
  queryData: queryListGroup,
} = useFetch({
  api: props.userType == 1 ? listTextGroup : userListTextGroup,
  params: {},
});

// 表格相关
const searchParams = ref({
  _id: '',
  use_status: 0,
  group_id: '',
});
const { loading, paging, tableData, queryTableData, delTableRow } = useTable({
  api: props.userType == 1 ? pageListText : pageUserListText,
  params: searchParams.value,
  options: {},
  callBack: () => {},
});

// 添加
const hanleModal = () => {
  if (props.userType == 1) {
    router.push({
      path: '/manage-center/text-list/text-create',
      query: {
        group_id: searchParams.value.group_id,
      },
    });
  } else {
    router.push({
      path: '/user-manage/user-text-list/user-text-create',
      query: {
        group_id: searchParams.value.group_id,
      },
    });
  }
};

// 删除
const handleDelete = (row) => {
  delTableRow({
    api: delText,
    params: { _id: row._id, delete_status: 1 },
  });
};

const handleUseStatus = (item) => {
  MessageBox({
    title: '确定使用该数据？',
    message: '操作不可逆，请谨慎操作',
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true;

        let res = await editeStatus({
          _id: item._id,
          use_status: 1,
        }).catch((err) => err);

        instance.confirmButtonLoading = false;

        if (res?.code !== 0) return;

        ElMessage.success('操作成功');
        queryTableData();
      }
      done();
    },
  });
};

const handleCopy = (row) => {
  copyText(row.content);
};

// 行拖拽
const rowDrop = () => {
  const tbody = document.querySelector('.table-template__table tbody');
  Sortable.create(tbody, {
    group: {
      name: 'shared',
      pull: true,
      put: true,
    },
    handle: '.table-drag-img',
    animation: 150,
    onEnd({ newIndex, oldIndex }) {
      console.log(newIndex, oldIndex, 'newIndex, oldIndex');

      const currRow = tableData.value.splice(oldIndex, 1)[0];

      tableData.value.splice(newIndex, 0, currRow);
    },
  });
};

// 列拖拽
const columnDrop = () => {
  const tr = document.querySelector('.table-template__table tr');
  Sortable.create(tr, {
    animation: 150,
    onEnd: ({ newIndex, oldIndex }) => {
      console.log(newIndex, oldIndex, 'newIndex, oldIndex');
    },
  });
};

const onGroupCreate = () => {
  modalStore.openModal('text-group-create');
};

const onGroupEdite = (item) => {
  modalStore.openModal('text-group-create', item);
};

const handleImageBatchUpdate = (selectionList) => {
  // modalStore.openModal('image-batch-update', { selectionList });
};

const onGroupDelete = (item) => {
  MessageBox({
    title: '确定删除该数据？',
    message: '操作不可逆，请谨慎操作',
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true;

        let res = await delTextGroup({
          _id: item._id,
          delete_status: 1,
        }).catch((err) => err);

        instance.confirmButtonLoading = false;

        if (res?.code !== 0) return;

        ElMessage.success('删除成功');
        queryListGroup();
      }
      done();
    },
  });
};

onMounted(() => {
  // rowDrop();
  // columnDrop();
});
</script>

<style lang="scss" scoped>
.table-template {
  display: flex;
  flex-direction: column;
}

.image-item {
  width: 40px;
  aspect-ratio: 9/16;
}

.table-group {
  height: 100%;
  display: flex;

  &__content {
    width: 100%;
    overflow: hidden;
    margin-left: 6px;
    padding: 20px;
    box-sizing: border-box;
    @include card-box;
  }
}

.table-drag-img {
  font-size: 20px;
  vertical-align: middle;
  cursor: grab;
  margin: 0;
  padding: 0;
}
</style>
